package com.ruoyi.report_chl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.ruoyi.common.utils.BigDecimalUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.syrw.annotation.ComputeReportResult;
import com.ruoyi.syrw.annotation.FIllBasicInfo;
import com.ruoyi.syrw.annotation.FIllBasicInfoForTaiZhang;
import com.ruoyi.report_tg.domain.TgsybgBaDetail;
import com.ruoyi.report_tg.domain.vo.TgsybgBaDetailVo;
import com.ruoyi.report_tg.mapper.TgsybgBaDetailMapper;
import com.ruoyi.sycs.service.IBiQualificationService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.report_chl.domain.bo.ChlFmhbgBsInfoBo;
import com.ruoyi.report_chl.domain.vo.ChlFmhbgBsInfoVo;
import com.ruoyi.report_chl.domain.ChlFmhbgBsInfo;
import com.ruoyi.report_chl.mapper.ChlFmhbgBsInfoMapper;
import com.ruoyi.report_chl.service.IChlFmhbgBsInfoService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 粉煤灰 报告Service业务层处理
 *
 * @author zyb
 * @date 2024-07-15
 */
@RequiredArgsConstructor
@Service
@DSTransactional
public class ChlFmhbgBsInfoServiceImpl implements IChlFmhbgBsInfoService {

    private final ChlFmhbgBsInfoMapper baseMapper;
    private final TgsybgBaDetailMapper detailMapper;

    private static final Long[] keys = {93L, 94L, 95L, 96L, 97L, 98L, 99L, 100L, 101L, 102L, 103L, 104L, 105L};

    private final IBiQualificationService biQualificationService;

    /**
     * 查询粉煤灰 报告
     */
    @Override
    @FIllBasicInfo
    public ChlFmhbgBsInfoVo queryById(Long excelId) {
        ChlFmhbgBsInfoVo chlFmhbgBsInfoVo = baseMapper.selectVoById(excelId);
        // 查询detail
        List<TgsybgBaDetailVo> baDetailVos = detailMapper.selectVoList(new LambdaQueryWrapper<TgsybgBaDetail>()
            .eq(TgsybgBaDetail::getExcelId, excelId));
        baDetailVos.forEach(v -> {
            v.setQualInfo(biQualificationService.queryById(v.getQualId()));
        });
        // 格式化 技术指标
        biQualificationService.compute(baDetailVos);
        // 转换成map形式
        Map<Long, TgsybgBaDetailVo> collect = baDetailVos.stream().collect(Collectors.toMap(TgsybgBaDetailVo::getQualId, v -> {
            return v;
        }));
        chlFmhbgBsInfoVo.setBaDetailVos(collect);

        // 生成结论 。 如果已经有值了则不需要生成结论。
        if (StrUtil.isNotEmpty(chlFmhbgBsInfoVo.getJiancjl()) && !"检测结论：".equals(chlFmhbgBsInfoVo.getJiancjl())) {
            return chlFmhbgBsInfoVo;
        }
        return jcjl(chlFmhbgBsInfoVo);
    }

    @Override
    @FIllBasicInfoForTaiZhang
    public ChlFmhbgBsInfoVo queryByIdForTaizhang(Long excelId) {
        ChlFmhbgBsInfoVo chlFmhbgBsInfoVo = baseMapper.selectVoById(excelId);
        // 查询detail
        List<TgsybgBaDetailVo> baDetailVos = detailMapper.selectVoList(new LambdaQueryWrapper<TgsybgBaDetail>()
            .eq(TgsybgBaDetail::getExcelId, excelId));
        baDetailVos.forEach(v -> {
            v.setQualInfo(biQualificationService.queryById(v.getQualId()));
        });
        // 格式化 技术指标
        biQualificationService.compute(baDetailVos);
        // 转换成map形式
        Map<Long, TgsybgBaDetailVo> collect = baDetailVos.stream().collect(Collectors.toMap(TgsybgBaDetailVo::getQualId, v -> {
            return v;
        }));
        chlFmhbgBsInfoVo.setBaDetailVos(collect);

        // 生成结论 。 如果已经有值了则不需要生成结论。
        if (StrUtil.isNotEmpty(chlFmhbgBsInfoVo.getJiancjl()) && !"检测结论：".equals(chlFmhbgBsInfoVo.getJiancjl())) {
            return chlFmhbgBsInfoVo;
        }

        // 台账
        if (CollUtil.isNotEmpty(collect)) {
            chlFmhbgBsInfoVo.setKey93(collect.get(93L) != null ? BigDecimalUtil.toString(collect.get(93L).getJiancjg()) : null);
            chlFmhbgBsInfoVo.setKey94(collect.get(94L) != null ? BigDecimalUtil.toString(collect.get(94L).getJiancjg()) : null);
            chlFmhbgBsInfoVo.setKey95(collect.get(95L) != null ? BigDecimalUtil.toString(collect.get(95L).getJiancjg()) : null);
            chlFmhbgBsInfoVo.setKey96(collect.get(96L) != null ? BigDecimalUtil.toString(collect.get(96L).getJiancjg()) : null);
            chlFmhbgBsInfoVo.setKey97(collect.get(97L) != null ? BigDecimalUtil.toString(collect.get(97L).getJiancjg()) : null);
            chlFmhbgBsInfoVo.setKey98(collect.get(98L) != null ? BigDecimalUtil.toString(collect.get(98L).getJiancjg()) : null);
            chlFmhbgBsInfoVo.setKey99(collect.get(99L) != null ? BigDecimalUtil.toString(collect.get(99L).getJiancjg()) : null);
            chlFmhbgBsInfoVo.setKey100(collect.get(100L) != null ? BigDecimalUtil.toString(collect.get(100L).getJiancjg()) : null);
            chlFmhbgBsInfoVo.setKey101(collect.get(101L) != null ? BigDecimalUtil.toString(collect.get(101L).getJiancjg()) : null);
            chlFmhbgBsInfoVo.setKey102(collect.get(102L) != null ? BigDecimalUtil.toString(collect.get(102L).getJiancjg()) : null);
            chlFmhbgBsInfoVo.setKey103(collect.get(103L) != null ? BigDecimalUtil.toString(collect.get(103L).getJiancjg()) : null);
            chlFmhbgBsInfoVo.setKey104(collect.get(104L) != null ? BigDecimalUtil.toString(collect.get(104L).getJiancjg()) : null);
        }
        return jcjl(chlFmhbgBsInfoVo);
    }

    /**
     * 查询粉煤灰 报告列表
     */
    @Override
    public TableDataInfo<ChlFmhbgBsInfoVo> queryPageList(ChlFmhbgBsInfoBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ChlFmhbgBsInfo> lqw = buildQueryWrapper(bo);
        Page<ChlFmhbgBsInfoVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询粉煤灰 报告列表
     */
    @Override
    public List<ChlFmhbgBsInfoVo> queryList(ChlFmhbgBsInfoBo bo) {
        LambdaQueryWrapper<ChlFmhbgBsInfo> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ChlFmhbgBsInfo> buildQueryWrapper(ChlFmhbgBsInfoBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ChlFmhbgBsInfo> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getTotalPage() != null, ChlFmhbgBsInfo::getTotalPage, bo.getTotalPage());
        lqw.eq(bo.getPage() != null, ChlFmhbgBsInfo::getPage, bo.getPage());
        lqw.eq(StringUtils.isNotBlank(bo.getBaogbh()), ChlFmhbgBsInfo::getBaogbh, bo.getBaogbh());
        lqw.eq(StringUtils.isNotBlank(bo.getJiancdwmc()), ChlFmhbgBsInfo::getJiancdwmc, bo.getJiancdwmc());
        lqw.eq(StringUtils.isNotBlank(bo.getGongcbwyt()), ChlFmhbgBsInfo::getGongcbwyt, bo.getGongcbwyt());
        lqw.eq(StringUtils.isNotBlank(bo.getYangpmc()), ChlFmhbgBsInfo::getYangpmc, bo.getYangpmc());
        lqw.eq(StringUtils.isNotBlank(bo.getYangpbh()), ChlFmhbgBsInfo::getYangpbh, bo.getYangpbh());
        lqw.eq(StringUtils.isNotBlank(bo.getYangpsl()), ChlFmhbgBsInfo::getYangpsl, bo.getYangpsl());
        lqw.eq(StringUtils.isNotBlank(bo.getYangpzt()), ChlFmhbgBsInfo::getYangpzt, bo.getYangpzt());
        lqw.eq(StringUtils.isNotBlank(bo.getYangpsj()), ChlFmhbgBsInfo::getYangpsj, bo.getYangpsj());
        lqw.eq(StringUtils.isNotBlank(bo.getYangpgg()), ChlFmhbgBsInfo::getYangpgg, bo.getYangpgg());
        lqw.eq(StringUtils.isNotBlank(bo.getJiancrq()), ChlFmhbgBsInfo::getJiancrq, bo.getJiancrq());
        lqw.eq(StringUtils.isNotBlank(bo.getChucrq()), ChlFmhbgBsInfo::getChucrq, bo.getChucrq());
        lqw.eq(StringUtils.isNotBlank(bo.getJincrq()), ChlFmhbgBsInfo::getJincrq, bo.getJincrq());
        lqw.eq(StringUtils.isNotBlank(bo.getShiytjwd()), ChlFmhbgBsInfo::getShiytjwd, bo.getShiytjwd());
        lqw.eq(StringUtils.isNotBlank(bo.getShiytjsd()), ChlFmhbgBsInfo::getShiytjsd, bo.getShiytjsd());
        lqw.eq(StringUtils.isNotBlank(bo.getJiancyj()), ChlFmhbgBsInfo::getJiancyj, bo.getJiancyj());
        lqw.eq(StringUtils.isNotBlank(bo.getPandyj()), ChlFmhbgBsInfo::getPandyj, bo.getPandyj());
        lqw.eq(StringUtils.isNotBlank(bo.getZhuyyqsbmcjbh()), ChlFmhbgBsInfo::getZhuyyqsbmcjbh, bo.getZhuyyqsbmcjbh());
        lqw.eq(StringUtils.isNotBlank(bo.getQuywz()), ChlFmhbgBsInfo::getQuywz, bo.getQuywz());
        lqw.eq(StringUtils.isNotBlank(bo.getWeitrwbh()), ChlFmhbgBsInfo::getWeitrwbh, bo.getWeitrwbh());
        lqw.eq(StringUtils.isNotBlank(bo.getTuycd()), ChlFmhbgBsInfo::getTuycd, bo.getTuycd());
        lqw.eq(StringUtils.isNotBlank(bo.getShengccj()), ChlFmhbgBsInfo::getShengccj, bo.getShengccj());
        lqw.eq(StringUtils.isNotBlank(bo.getPih()), ChlFmhbgBsInfo::getPih, bo.getPih());
        lqw.eq(StringUtils.isNotBlank(bo.getDaibsl()), ChlFmhbgBsInfo::getDaibsl, bo.getDaibsl());
        lqw.eq(StringUtils.isNotBlank(bo.getFujsm()), ChlFmhbgBsInfo::getFujsm, bo.getFujsm());
        lqw.eq(StringUtils.isNotBlank(bo.getJiancjl()), ChlFmhbgBsInfo::getJiancjl, bo.getJiancjl());
        lqw.eq(StringUtils.isNotBlank(bo.getShigwtdw()), ChlFmhbgBsInfo::getShigwtdw, bo.getShigwtdw());
        lqw.eq(StringUtils.isNotBlank(bo.getGongcmc()), ChlFmhbgBsInfo::getGongcmc, bo.getGongcmc());
        lqw.eq(StringUtils.isNotBlank(bo.getShebIds()), ChlFmhbgBsInfo::getShebIds, bo.getShebIds());
        lqw.eq(StringUtils.isNotBlank(bo.getBgFlag()), ChlFmhbgBsInfo::getBgFlag, bo.getBgFlag());
        lqw.eq(StringUtils.isNotBlank(bo.getJiancyjIds()), ChlFmhbgBsInfo::getJiancyjIds, bo.getJiancyjIds());
        lqw.eq(StringUtils.isNotBlank(bo.getPandyjIds()), ChlFmhbgBsInfo::getPandyjIds, bo.getPandyjIds());
        return lqw;
    }

    /**
     * 新增粉煤灰 报告
     */
    @Override
    public Boolean insertByBo(ChlFmhbgBsInfoBo bo) {
        ChlFmhbgBsInfo add = BeanUtil.toBean(bo, ChlFmhbgBsInfo.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setExcelId(add.getExcelId());
            // 新增详细 多个keys
            ArrayList<TgsybgBaDetail> details = new ArrayList<>(13);
            for (Long key : keys) {
                details.add(new TgsybgBaDetail(add.getExcelId(), key));
            }
            detailMapper.insertBatch(details);
        }
        return flag;
    }

    /**
     * 修改粉煤灰 报告
     */
    @Override
    @ComputeReportResult
    public Boolean updateByBo(ChlFmhbgBsInfoBo bo) {
        // 增加对 是否合格 的填充
        fillExcelResult(bo);
        ChlFmhbgBsInfo update = BeanUtil.toBean(bo, ChlFmhbgBsInfo.class);
        validEntityBeforeSave(update);
        boolean flag = baseMapper.updateById(update) > 0;
        if (flag) {
            detailMapper.updateBatchById(BeanUtil.copyToList(bo.getBaDetailVos().values(), TgsybgBaDetail.class));
        }
        return flag;
    }

    private void fillExcelResult(ChlFmhbgBsInfoBo bo) {
        if (CollUtil.isNotEmpty(bo.getBaDetailVos())) {
            for (TgsybgBaDetailVo detailVo : bo.getBaDetailVos().values()) {
                if ("不符合".equals(detailVo.getJiegpd())) {
                    bo.setExcelResult(2);
                    return;
                }
            }
            bo.setExcelResult(1);
            return;
        }
        bo.setExcelResult(0);
    }

    public boolean isWell(Long excelId) {
        return baseMapper.selectVoById(excelId).getExcelResult() != 2;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ChlFmhbgBsInfo entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除粉煤灰 报告
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 生成 粉煤灰 报告 检测结论
     */
    @Override
    public ChlFmhbgBsInfoVo jcjl(ChlFmhbgBsInfoVo vo) {
//        if (StrUtil.isEmpty(vo.getPandyj())) {
//            return vo;
//        }
        StringBuilder result = new StringBuilder("检测结论：经检测，该粉煤灰");
        boolean haveShicz = false;
        for (TgsybgBaDetailVo detailVo : vo.getBaDetailVos().values()) {
            if ("实测值".equals(detailVo.getJiegpd())) {
                result.append(detailVo.getQualName()).append("为").append(BigDecimalUtil.stpTrailZero(detailVo.getJiancjg())).append(detailVo.getQualUnit()).append("，");
                haveShicz = true;
            }
        }
        if (haveShicz) {
            result.append("其他指标符合");
        } else {
            result.append("所检指标符合");
        }
        result.append("JTG/T 3650-2020").append("《公路桥涵施工技术规范》F类Ⅰ级粉煤灰技术要求。");
        vo.setJiancjl(result.toString());
        return vo;
    }
}
